#include "lua_function.h"

#include <stdlib.h>
#include <string.h>

#include <event.h>

#include "socketinfo.h"

static int bin_to_int(lua_State * L)
{
	if(!lua_isstring(L, -1) ) {
		return 0;
	}

	size_t len = 0;
	const char * ptr = lua_tolstring(L, -1, &len);
	if (len < sizeof(int32_t)) {
		return 0;
	}
	int32_t val = 0;
	memcpy(&val, ptr, sizeof(val));
	lua_pushinteger(L, val);
	return 1;
}

static int bin_from_int(lua_State * L)
{
	if(!lua_isnumber(L, -1) ) {
		return 0;
	}

	int32_t val = lua_tointeger(L, -1);
	lua_pushlstring(L, (const char*)&val, sizeof(val));
	return 1;
}


static int conn_close(lua_State * L)
{
	if(!lua_islightuserdata(L, -1)) {
		return 0;
	}

	struct connection * conn = (struct connection*)lua_touserdata(L, -1);
	release_connection(conn);
	lua_pushboolean(L, 1);
	return 1;
}

static int conn_write(lua_State * L)
{
	if(!lua_islightuserdata(L, -2)) {
		return 0;
	}

	if(!lua_isstring(L, -1)) {
		return 0;
	}

	struct connection * conn = (struct connection*)lua_touserdata(L, -2);
	size_t len = 0;
	const char * ptr = lua_tolstring(L, -1, &len);
	bufferevent_write(conn->bev, ptr, len);
	lua_pushboolean(L, 1);
	return 1;
}

luaL_Reg bin_functions[] = {
	{"to_int", bin_to_int},
	{"from_int", bin_from_int},
	{0,0},
};

luaL_Reg conn_functions[] = {
	{"close", conn_close},
	{"write", conn_write},
	{0,0},
};

int registe_function(lua_State * L)
{
	luaL_register(L, "bin", bin_functions);
	luaL_register(L, "connection", conn_functions);
	return 0;
}
